<?php

namespace ticket\modules\backend\models;

use Yii;

/**
 * This is the model class for table "tk_pay_config".
 *
 * @property int $id
 * @property int $app_id
 * @property string $channelMerId
 * @property int $appId
 * @property int $aid
 * @property string $channelId
 * @property string $aes_key
 * @property string $aes_iv
 * @property string $key
 * @property int $state
 * @property string $create_time
 */
class PayConfig extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'tk_pay_config';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['app_id'], 'required'],
            [['app_id', 'appId', 'aid', 'state'], 'integer'],
            [['create_time'], 'safe'],
            [['channelMerId'], 'string', 'max' => 32],
            [['channelId'], 'string', 'max' => 64],
            [['aes_key', 'aes_iv', 'key'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'app_id' => 'App ID',
            'channelMerId' => 'Channel Mer ID',
            'appId' => 'App ID',
            'aid' => 'Aid',
            'channelId' => 'Channel ID',
            'aes_key' => 'Aes Key',
            'aes_iv' => 'Aes Iv',
            'key' => 'Key',
            'state' => 'State',
            'create_time' => 'Create Time',
        ];
    }


    public function getInfo($app_id)
    {
        $data = self::find()->where('app_id = :aid',[':aid' => $app_id])->asArray()->one();
        return $data;
    }


    public function setPayConfig($app_id,$params)
    {
        $params['create_time'] = date("Y-m-d H:i:s");
        $params['app_id'] = $app_id;

        $data = [
            'PayConfig' => $params
        ];
        if ($this->load($data) and $this->validate()){
            $model = self::find()->where('app_id = :aid',[':aid' => $app_id])->one();
            if (!is_null($model)){
                $model->channelMerId = $params['channelMerId'];
                $model->appId = $params['appId'];
                $model->aid = $params['aid'];
                $model->channelId = $params['channelId'];
                $model->aes_key = $params['aes_key'];
                $model->aes_iv = $params['aes_iv'];
                $model->key = $params['key'];
                $model->state = $params['state'];
                if ($model->save(0)){
                    return true;
                }
            }else{
                if ($this->save(0)){
                    return true;
                }
            }
        }
        return false;
    }
}
